package com.heima.article.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.feign.BehaviorFeign;
import com.heima.article.mapper.ApCollectionMapper;
import com.heima.article.service.ApCollectionService;
import com.heima.model.article.dtos.CollectionBehaviorDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApCollection;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.threadlocal.AppThreadLocalUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
@Transactional
public class ApCollectionServiceImpl extends ServiceImpl<ApCollectionMapper, ApCollection> implements ApCollectionService {

    @Autowired
    BehaviorFeign behaviorFeign;

    @Override
    public ResponseResult saveCollectionOrNotCollection(CollectionBehaviorDto dto) {
        //检查参数
        if (dto==null||(!dto.getOperation().equals((short)0)&&!dto.getOperation().equals((short)1))||dto.getEntryId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        Integer userID = AppThreadLocalUtils.getUser().getId();
        //根据用户id 或设备id获取行为实体 如果没有 返回
        ApBehaviorEntry enrty = behaviorFeign.getEnrty(userID, dto.getEquipmentId());
        if (enrty==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"没有行为实体");
        }
        //根据文章id和行为实体id 查询收藏表 如果没有 并且为收藏 0 保存
        ApCollection collect = getOne(Wrappers.<ApCollection>lambdaQuery().eq(ApCollection::getEntryId, enrty.getId())
                .eq(ApCollection::getArticleId, dto.getEntryId()));

        if (collect==null&&dto.getOperation().equals((short)0)){
            ApCollection newCollect = new ApCollection();
            newCollect.setArticleId(dto.getEntryId());
            newCollect.setCollectionTime(new Date());
            newCollect.setEntryId(enrty.getId());
            newCollect.setPublishedTime(dto.getPublishedTime());
            newCollect.setType(dto.getType());
            save(newCollect);
        }

        if (collect!=null&&dto.getOperation().equals((short)1)){
            //如果为取消收藏 1  删除此收藏表
            removeById(collect.getId());
        }

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
